<template>
    <el-col :span="12">
        <el-form-item label="默认值类型" prop="defaultValueType">
            <el-select
                v-model="form.defaultValueType"
                placeholder="请选择"
                :disabled="disabled['defaultValueType']"
                clearable
                @change="
                    () => {
                        form.defaultValue = undefined;
                        form.defaultItem = undefined;
                    }
                "
            >
                <el-option label="Constant字符常量" value="CONSTANT" />
                <el-option label="Spi调用" value="SPI" />
                <el-option label="数据字典" value="DICT" />
                <el-option label="标签" value="TAG" />
                <!-- <el-option label="组织机构" value="DEPT" />-->
            </el-select>
        </el-form-item>
    </el-col>
    <el-col :span="12"></el-col>
    <el-col :span="12" v-if="form.defaultValueType === 'CONSTANT'">
        <el-form-item label="默认值" prop="defaultValue" :show-message="false">
            <el-input v-model="form.defaultValue" placeholder="请输入默认值" maxlength="50" />
        </el-form-item>
    </el-col>
    <template v-if="form.defaultValueType === 'SPI'">
        <el-col :span="12">
            <el-form-item label="Spi实现类" prop="defaultValue" :show-message="false">
                <DynamicSelect
                    v-model="form.defaultItem"
                    :fetch-options="getSPIOptions"
                    :reload-deps="[form.defaultValueType]"
                />
            </el-form-item>
        </el-col>
    </template>
    <template v-if="form.defaultValueType === 'DICT'">
        <el-col :span="12">
            <el-form-item label="数据字典" prop="defaultItem" :show-message="false">
                <DynamicSelect
                    :disabled="disabled['defaultItem']"
                    v-model="form.defaultItem"
                    :fetch-options="getDictOptions"
                    :reload-deps="[form.defaultValueType]"
                />
            </el-form-item>
        </el-col>
        <el-col :span="12">
            <el-form-item label="默认值" prop="defaultValue" :show-message="false">
                <DynamicSelect
                    :model-value="getDefaultValue(form.defaultValue)"
                    :reload-deps="[() => form.defaultItem]"
                    :fetch-options="getDictValues"
                    :multiple="multiple"
                    @update:model-value="onDefaultValueChange"
                />
            </el-form-item>
        </el-col>
    </template>
    <template v-if="form.defaultValueType === 'TAG'">
        <el-col :span="12">
            <el-form-item label="标签分类" prop="defaultItem" :required="!!form.defaultValueType" :show-message="false">
                <DynamicSelect
                    :disabled="disabled['defaultItem']"
                    v-model="form.defaultItem"
                    :fetch-options="getTagOptions"
                    :reload-deps="[form.defaultValueType]"
                />
            </el-form-item>
        </el-col>
        <el-col :span="12">
            <el-form-item label="默认值" prop="defaultValue" :show-message="false">
                <DynamicSelect
                    :model-value="getDefaultValue(form.defaultValue)"
                    :reload-deps="[() => form.defaultItem]"
                    :fetch-options="getTagValues"
                    :multiple="multiple"
                    @update:model-value="onDefaultValueChange"
                />
            </el-form-item>
        </el-col>
    </template>
    <template v-if="form.defaultValueType === 'DEPT'">
        <el-col :span="12">
            <el-form-item label="默认值" prop="defaultValue" :show-message="false">
                <DynamicSelect v-model="form.defaultValue" :fetch-options="getDeptOptions" />
            </el-form-item>
        </el-col>
    </template>
</template>
<script setup lang="ts">
import { computed, type Reactive } from 'vue';
import { DynamicSelect } from '@great/components';
import {
    runLabelService,
    systemDeptService,
    systemDictDataService,
    systemDictTypeService,
    systemSpiService
} from '@great/services';
import { multipleValueSeparator } from '@great/utils';

interface IProps {
    form: Reactive<any>;
}
const props = defineProps<IProps>();
const disabled = ref({});

async function getDictOptions() {
    const res = await systemDictTypeService.optionselect();
    return (res?.data || []).map(item => {
        return { label: item.dictName, value: String(item.dictType) };
    });
}
async function getDictValues() {
    if (!props.form.defaultItem) {
        return [];
    }
    const res = await systemDictDataService.listData({
        pageNum: '1',
        pageSize: '10000',
        dictType: props.form.defaultItem
    } as any);
    return (res?.rows || []).map(item => {
        return { label: item.dictLabel, value: item.dictValue };
    });
}
async function getSPIOptions() {
    const res = await systemSpiService.getListByType('DEFAULT_VALUE');
    return res.data.map(item => {
        return { label: item.handlerName, value: item.handlerName };
    });
}
async function getTagOptions() {
    const res = await runLabelService.getCategory();
    return [...res.data.CUSTOM, ...res.data.INNER].map(item => {
        return { label: item.labelTypeName, value: item.labelTypeNo };
    });
}
async function getTagValues() {
    if (!props.form.defaultItem) {
        return [];
    }
    const res = await runLabelService.getLabelTree({
        labelTypeNo: props.form.defaultItem
    });

    function loop(list) {
        return list.map(item => {
            return {
                label: item.labelName,
                value: item.labelNo,
                children: loop(item.childLabel)
            };
        });
    }

    return loop(res.data);
}

async function getDeptOptions() {
    const res = await systemDeptService.listDept();
    return listToTree(res?.data || []);
}

function listToTree(list: any[] = []) {
    const tree: any[] = [];
    const lookup = {};

    list.forEach(item => {
        lookup[item['deptId']] = { label: item.deptName, value: String(item.deptId), children: [] };
    });
    list.forEach(item => {
        const node = lookup[item['deptId']];
        if (item['parentId'] === 0) {
            // 根节点
            tree.push(node);
        } else {
            if (lookup[item['parentId']]) {
                lookup[item['parentId']]['children'].push(node);
            }
        }
    });

    return tree;
}

const multiple = computed(() => props.form['multivalued']);

function getDefaultValue(value: any) {
    if (multiple.value) {
        return value ? value?.split(multipleValueSeparator) : [];
    }
    return value;
}
function onDefaultValueChange(value) {
    props.form.defaultValue = []
        .concat(value)
        .filter(item => !!item)
        .join(multipleValueSeparator);
}

const defaultValueType = ref('');
watch(
    () => props.form.additionalDefinition,
    value => {
        const _defaultValueType = value.dataType?.value?.toUpperCase();
        if (_defaultValueType === 'DICT' || _defaultValueType === 'TAG') {
            props.form.defaultValueType = _defaultValueType;
            props.form.defaultItem = value.dataType.config?.dictName || value.dataType.config?.tagName;
            disabled.value['defaultValueType'] = true;
            disabled.value['defaultItem'] = true;
            if (defaultValueType.value && defaultValueType.value !== _defaultValueType) {
                props.form.defaultValue = undefined;
            }
        } else {
            disabled.value = {};
        }
    },
    {
        deep: true
    }
);
</script>
<style scoped lang="scss"></style>
